package com.example.demo.handler;

import com.example.demo.vo.Result;
import com.example.demo.vo.ResultCode;
import com.example.demo.vo.UserNotFoundException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录失败处理器，一般是用户密码错误
 *
 * @author star
 */
@Component
@AllArgsConstructor
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Result result= null;
        if (exception instanceof InternalAuthenticationServiceException){
            result=Result.error(ResultCode.CLIENT_A0114);
        }else if (exception instanceof UserNotFoundException){
            result=Result.error(ResultCode.CLIENT_A0201);
        }else if (exception instanceof BadCredentialsException){
            result=Result.error(ResultCode.CLIENT_A0210);
        }else {
            result=Result.clientError();
        }

        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
